import { getHistories } from '@/utils/storage';

const initialState = {
  historySearch: getHistories(),
  resultList: [] as resultListType[],
  suggestList: [] as string[],
};
export type resultListType = {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: string;
  pubdate: string;
  cover: {
    type: string;
    images: string[];
  };
  like_count: string;
  collect_count: string;
};
export type searchActionType =
  | { type: 'search/history'; payload: string }
  | { type: 'search/clear' }
  | { type: 'search/result'; payload: resultListType[] }
  | { type: 'search/suggest'; payload: string[] }
  | { type: 'search/clearSuggest' }
  | { type: 'search/clearRessult' };

export default function searchReducer(
  state = initialState,
  action: searchActionType
) {
  switch (action.type) {
    case 'search/history':
      const newList = state.historySearch.filter(
        (item) => item !== action.payload
      );
      return {
        ...state,
        historySearch: [action.payload, ...newList],
      };
    case 'search/clear':
      return {
        ...state,
        historySearch: [],
      };
    case 'search/result':
      return {
        ...state,
        resultList: [...state.resultList, ...action.payload],
      };
    case 'search/suggest':
      return {
        ...state,
        suggestList: [...action.payload.filter((item) => item)],
      };
    case 'search/clearSuggest':
      return {
        ...state,
        suggestList: [],
      };
    case 'search/clearRessult':
      return {
        ...state,
        resultList: [],
      };

    default:
      return state;
  }
}
